/**
 * 知乎例子
 **/

import React, {Component} from 'react';
import {StyleSheet, FlatList, Button, Text, View, TouchableHighlight, Image, RefreshControl} from 'react-native';
import DemoBottomTab from "./DemoBottomTab";
import DemoZhiHuWebView from "./DemoZhiHuWebView";

export default class DemoZhiHu extends Component {
    static defaultProps = {
        url: "https://news-at.zhihu.com/api/4/news/before/",
    };

    //设置顶部导航栏的内容
    static navigationOptions = ({navigation, screenProps}) => ({
        //左侧标题
        headerTitle: '知乎日报',
        //设置跳转页面左侧返回箭头后面的文字，默认是上一个页面的标题
        headerBackTitle: null,
        //顶部标题栏的样式
        headerStyle: styles.headerStyle,
        //顶部标题栏文字的样式
        headerTitleStyle: styles.headerTitleStyle,
    });

    constructor(props) {
        super(props);
        this.flatList = '';
        //设置数据
        this.state = {
            curDate: 0,
            list: [],
            refreshing: false,
        };
    }

    componentDidMount() {
        this._onRefrash();
    }

    render() {
        return (
            <FlatList
                ref={ref=>this.flatList=ref}
                keyExtractor={(item, index) => index.toString()}
                data={this.state.list}
                extraData={this.state}
                renderItem={this._renderItem.bind(this)}
                ItemSeparatorComponent={this._ItemSeparator.bind(this)}
                refreshControl={
                    <RefreshControl
                        refreshing={this.state.refreshing}
                        onRefresh={this._onRefrash.bind(this)}
                    />
                }
                onEndReached={this._onLoadMore.bind(this)}
            />
        );
    }

    _renderItem(item) {
        const {navigate} = this.props.navigation;
        return (
            //渲染item
            <TouchableHighlight underlayColor='#CFCFCF' onPress={() => {
                //跳转详情页面
                navigate('DemoZhiHuWebView', {
                    "id":item.item.id,
                });
            }}>
                <View style={styles.container}>
                    <Image
                        source={{uri:item.item.images[0]}}
                        style={styles.itemImage}
                    />
                    <Text style={styles.itemText}>{item.item.title}</Text>
                </View>
            </TouchableHighlight>
        );
    }

    //刷新数据
    _onRefrash() {
        let time = new Date().Format('yyyyMMdd');
        this.setState({refreshing:true});
        this._getNewList(time, false);
        this.setState({refreshing:false});
    }

    //加载更多
    _onLoadMore() {
        //不在加载中，才可以加载更多
        if (!this.state.refreshing) {
            let time = ""+this.state.curDate;
            let tmpTime = new Date(time.substring(0, 4), time.substring(4, 6)-1, time.substring(6));
            let queTime = tmpTime.Format("yyyyMMdd");
            console.log("time:"+time+"  tmpTime:"+tmpTime+"  queTime:"+queTime);
            this.setState({refreshing:true});
            this._getNewList(queTime, true);
            this.setState({refreshing:false});
        }
    }

    _ItemSeparator() {
        return <View style={{backgroundColor: '#DCDCDC', height: 1, marginLeft: 10, marginRight: 10}}/>
    }

    //获取新列表
    _getNewList(time, isLoadMore) {
        this.setState({refreshing:true});
        let requestUrl = this.props.url + time;
        console.log("请求url:"+requestUrl+ "  isLoadMore:"+isLoadMore);
        fetch(requestUrl)
            .then((response) => response.json())
            .then((jsonObj) => {
                //请求成功，数据封装
                let data = [];
                if (isLoadMore) {
                    //加载更多
                    data = this.state.list.concat(jsonObj["stories"]);
                } else {
                    //刷新
                    data = jsonObj["stories"];
                }
                console.log("更新时间:"+jsonObj["date"]);
                this.setState({
                    curDate:jsonObj["date"],
                    list:data,
                });
            })
            .catch((error) => console.log(error));
    }
}


Date.prototype.Format = function (fmt) { // author: meizz
    var o = {
        "M+": this.getMonth() + 1, // 月份
        "d+": this.getDate(), // 日
        "h+": this.getHours(), // 小时
        "m+": this.getMinutes(), // 分
        "s+": this.getSeconds(), // 秒
        "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
        "S": this.getMilliseconds() // 毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

const styles = StyleSheet.create({
    container: {
        alignItems: "center",
        flexDirection: 'row',
        paddingLeft: 10,
        paddingTop:10,
        paddingBottom: 10,
    },
    headerStyle: {
        backgroundColor: '#4398ff',
    },
    headerTitleStyle: {
        //标题的文字颜色
        color: 'white',
        //设置标题的大小
        fontSize: 18,
        //居中显示
        alignSelf: 'center',
    },
    itemImage: {
        height: 100,
        width: 100
    },
    itemText: {
        marginLeft:10,
        fontSize: 16,
        width:240,
        letterSpacing:3,
        lineHeight:28
    }
});